#include "Md3.h"


Md3::Md3()
{
}


Md3::~Md3()
{
}

void Md3::Load(std::string path)
{
	FILE* file = std::fopen(path.c_str(), "rb");

	std::fseek(file, 0, SEEK_SET);
	std::fread(&m_oHeader, sizeof(Md3Header), 1, file);

	m_pFrames = new Md3Frame[m_oHeader.FrameCount];
	m_pTags = new Md3Tag[m_oHeader.FrameCount * m_oHeader.TagCount];
	m_pMeshs = new Md3Mesh[m_oHeader.MeshCount];

	Md3Bone* m_pBones = new Md3Bone[m_oHeader.FrameCount];
	std::fread(m_pBones, sizeof(Md3Bone), m_oHeader.FrameCount, SEEK_SET);
	delete [] m_pBones;

	std::fread(m_pTags, sizeof(Md3Tag), m_oHeader.FrameCount * m_oHeader.TagCount, file);

	std::fseek(file, m_oHeader.FrameOffset, SEEK_SET);
	std::fread(m_pFrames, sizeof(Md3Frame), m_oHeader.FrameCount, file);

	std::fseek(file, m_oHeader.MeshOffset, SEEK_SET);

	long meshOffset = ftell(file);

	for(int a = 0; a < m_oHeader.MeshCount; a++)
	{
		Md3MeshInformation meshInformation;
		Md3Mesh* mesh = &m_pMeshs[a];

		std::fseek(file, meshOffset, SEEK_SET);
		std::fread(&meshInformation, sizeof(Md3MeshInformation), 1, file);

		mesh->Skins					= new Md3Skin[meshInformation.SkinCount];
		mesh->Triangles				= new Md3Triangle[meshInformation.TriangleCount];
		mesh->Vertices				= new Md3Vertex[meshInformation.VertexCount];
		mesh->TextureCoordinates	= new Vector2f[meshInformation.VertexCount];

		std::fseek(file, meshInformation.SkinOffset, SEEK_CUR);
		std::fread(mesh->Skins, sizeof(Md3Skin), meshInformation.SkinCount, file);

		std::fseek(file, meshInformation.TriangleOffset, SEEK_CUR);	// TODO: wrong.
		std::fread(mesh->Triangles, sizeof(Md3Triangle), meshInformation.TriangleCount, file);

		std::fseek(file, meshInformation.TextureCoordinateOffset, SEEK_CUR);
		std::fread(mesh->TextureCoordinates, sizeof(Vector2f), meshInformation.VertexCount, file);	// TODO: Use vertex count for element count?

		std::fseek(file, meshInformation.VertexOffset, SEEK_CUR);	// TODO: Wrong.
		std::fread(mesh->Vertices, sizeof(Md3Vertex), meshInformation.VertexCount, file);
	}

	std::fclose(file);
}